# -*- encoding:utf-8 -*-

import sys
import hashlib
from SVM import sa
import hmac
import base64
from socket import *
import json, time, threading
from websocket import create_connection
import websocket           #WebSocket使得客户端和服务器之间的数据交换变得更加简单，允许服务端主动向客户端推送数据。在WebSocket API中，浏览器和服务器只需要完成一次握手，两者之间就直接可以创建持久性的连接，并进行双向数据传输。
from urllib.parse import quote
import logging
import pyaudio

# reload(sys)
# sys.setdefaultencoding("utf8")
logging.basicConfig()

base_url = "ws://rtasr.xfyun.cn/v1/ws"
app_id = "9ca40ebd"
api_key = "2d131312f65975da6d087cce20d63c01"
file_path = r"./test_1.pcm"

pd = "edu"

end_tag = "{\"end\": true}"


class Client():
    def __init__(self):
        ts = str(int(time.time()))
        tt = (app_id + ts).encode('utf-8')
        md5 = hashlib.md5()   #登录网站的用户名密码数据库是不会以明文密码进行存储的，简单的，可以通过摘要算法得到一个长度固定的数据块。
        md5.update(tt)
        baseString = md5.hexdigest()    #返回摘要，作为十六进制数据字符串值
        baseString = bytes(baseString, encoding='utf-8')  #如果 source 为字符串，则按照指定的 encoding 将字符串转换为字节序列；

        apiKey = api_key.encode('utf-8')
        signa = hmac.new(apiKey, baseString, hashlib.sha1).digest()
        signa = base64.b64encode(signa)
        signa = str(signa, 'utf-8')

        self.ws = create_connection(base_url + "?appid=" + app_id + "&ts=" + ts + "&signa=" + quote(signa))
        self.trecv = threading.Thread(target=self.recv)   #多线程执行recv函数
        self.trecv.start()

    def send(self):
        rate=16000                  #采样频率
        format = pyaudio.paInt16    #采样位
        channels = 1                #声道数
        chunks = 1280               #缓冲区
        p=pyaudio.PyAudio()
        stream = p.open(rate=rate,channels=channels,format=format,frames_per_buffer=chunks,input=True)
        while True:
            l=[]
            for i in range(3):
                data = stream.read(chunks)
                l.append(data)

            self.ws.send("".encode().join(l))
    def recv(self):
        try:
            while self.ws.connected:
                result = str(self.ws.recv())
                if len(result) == 0:
                    print("receive result end")
                    break
                result_dict = json.loads(result)
                # 解析结果
                import datetime
                if result_dict["action"] == "started":
                    time1=time.time()
                    print(str(datetime.datetime.now())+"------->"+"handshake success, result: " + result)

                if result_dict["action"] == "result":
                    result_1 = result_dict
                    result_2 = json.loads(result_1["data"])["cn"]["st"]["rt"]
                    a=''
                    list_1 = []
                    for i in result_2:

                        for x in i["ws"]:
                            w= x['cw'][0]['w']
                            wp=x['cw'][0]["wp"]
                            if wp !='s':
                                a += w
                                list_1.append(a)
                    if not list_1:
                        print(datetime.datetime.now(), '未听清，请再说一遍')
                    else:
                        import re
                        pattern = re.compile(r'[\u4e00-\u9fa5]')  # 用于匹配至少一个数字
                        m = pattern.findall(list_1[-1])  # 查找头部，没有匹配
                        c = ''
                        for i in m:
                            c += str(i)
                        print(datetime.datetime.now(),"--------->",c)
                        svc=sa(c)
                        print(svc)

                if result_dict["action"] == "error":
                    print("rtasr error: " + result)
                    self.ws.close()
                    return
        except websocket.WebSocketConnectionClosedException:
            print("receive result end")

    def close(self):
        self.ws.close()
        print("connection closed")


if __name__ == '__main__':
    client = Client()
    client.send()
